import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';

class WechatPlugs{
  static const MethodChannel _wechatPayChannel = MethodChannel("flutter_wechat_plugs");

  ///微信支付
  static Future doPay({required WxPayRequest request,required ValueChanged<bool> changed})async{
    try{
      _wechatPayChannel.setMethodCallHandler((call) {
        switch(call.method){
          case "onPaySuccess":
            changed.call(true);
            break;
          case "onPayFail":
            changed.call(false);
            Fluttertoast.showToast(msg: "微信支付失败,code=${call.arguments["code"]},error=${call.arguments["errorMsg"]}");
            break;
        }
        return Future.value(true);
      });
      await _wechatPayChannel.invokeMethod("doPay",request.toJson());
    }catch(e){
      if(e is PlatformException && e.message!=null){
        Fluttertoast.showToast(msg: e.message!);
      }
      return Future.error(e);
    }
  }
}

///微信支付请求参数
class WxPayRequest{
  String partnerId;
  String prepayId;
  String packageValue;
  String nonceStr;
  String timeStamp;
  String sign;

  WxPayRequest({
    required this.partnerId,
    required this.prepayId,
    required this.packageValue,
    required this.nonceStr,
    required this.timeStamp,
    required this.sign});


  factory WxPayRequest.fromJson(Map<String,dynamic> json)=>WxPayRequest(
      partnerId: json["partnerid"],
      prepayId:json["prepayid"],
      packageValue:json["package"],
      nonceStr:json["noncestr"],
      timeStamp:json["timestamp"],
      sign:json["sign"]
  );

  Map toJson(){
    return {
      "partnerId":partnerId,
      "prepayId":prepayId,
      "packageValue":packageValue,
      "nonceStr":nonceStr,
      "timeStamp":timeStamp,
      "sign":sign
    };
  }
}